package com.android.microweather;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;

public class CitySelectionActivity extends Activity {
	public static final int 	GET_CITY = 1;
	public static final String	BUNDLE_PARAM_COUNTRY = "country";
	public static final String	BUNDLE_PARAM_CITY 	= "city";
	public static final String	BUNDLE_PARAM_CITY_ID = "cityId";
	
	private static final int	DIALOG_ERROR_INCOMPLETE_FIELDS = 1;
	private static final int	DIALOG_ERROR_CITY_ALREADY_EXISTS = 2;
	
	private ArrayList<String> 	countryNames = null;
	private ArrayList<String> 	cityNames = null;
	private ArrayList<String>	cityIds = null;	// Each city has a unique ID

	private String				selectedCityId = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_selection);
		
		try {
			// Initialize auto-complete text views
			initCountryList();
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_dropdown_item_1line, countryNames);
			AutoCompleteTextView countriesTextView =
									(AutoCompleteTextView) findViewById(R.id.city_selection_country_autocomplete);
			countriesTextView.setAdapter(adapter);
			countriesTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					try {
						String selectedCountry = (String) ((TextView)view).getText();
						
						initCityList(selectedCountry);
						
						ArrayAdapter<String> adapter = new ArrayAdapter<String>(CitySelectionActivity.this,
								android.R.layout.simple_dropdown_item_1line, cityNames);
						AutoCompleteTextView citiesTextView =
							(AutoCompleteTextView) findViewById(R.id.city_selection_city_autocomplete);
						citiesTextView.setAdapter(adapter);
						// When country selection completes (i.e. this method is invoked
						// we've got to 1: fill up city list (what we've done right above)
						// 2: clear city input box (what we're doing right below)
						citiesTextView.setText("");
					}
					catch (IOException e) {
						// TODO
					}
				}
			});
			
			AutoCompleteTextView citiesTextView =
				(AutoCompleteTextView) findViewById(R.id.city_selection_city_autocomplete);
			citiesTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					String selectedCity = (String) ((TextView)view).getText();
					for (int i = 0; i < cityNames.size(); i++) {
						if (cityNames.get(i).equals(selectedCity)) {
							selectedCityId = cityIds.get(i);
							break;
						}
					}
				}
			});

			
			// Init 'Ok' button
			Button okButton = (Button) findViewById(R.id.city_selection_submit);
			okButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					AutoCompleteTextView citiesTextView =
						(AutoCompleteTextView) findViewById(R.id.city_selection_city_autocomplete);
					AutoCompleteTextView countriesTextView =
						(AutoCompleteTextView) findViewById(R.id.city_selection_country_autocomplete);
					String cityName = citiesTextView.getText().toString();
					String countryName = countriesTextView.getText().toString();
					if (cityName.length() == 0 || countryName.length() == 0)
						showDialog(DIALOG_ERROR_INCOMPLETE_FIELDS);
					else {
						DataModel model = DataModel.getInstance();
						boolean cityExists = false;
						for (City city : model.getCityList())
							if (city.getName().equals(cityName) && city.getCountryName().equals(countryName)) {
								cityExists = true;
								break;
							}
						if (cityExists)
							showDialog(DIALOG_ERROR_CITY_ALREADY_EXISTS);
						else {
							Bundle params = new Bundle();
							params.putString(BUNDLE_PARAM_COUNTRY, countryName);
							params.putString(BUNDLE_PARAM_CITY, cityName);
							params.putString(BUNDLE_PARAM_CITY_ID, selectedCityId);
							Intent i = new Intent();
							i.putExtras(params);
							setResult(RESULT_OK, i);
							finish();
						}
					}
				}
			});
		}
		catch (IOException e) {
			// TODO
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog result = null;
		switch (id) {
			case DIALOG_ERROR_INCOMPLETE_FIELDS:
			case DIALOG_ERROR_CITY_ALREADY_EXISTS:
				AlertDialog dialog = new AlertDialog.Builder(this)
					.setIcon(R.drawable.alert_dialog_icon)
					.setTitle(R.string.dialog_title_error)
					.setPositiveButton(R.string.dialog_alert_ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					})
					.create();

				if (id == DIALOG_ERROR_INCOMPLETE_FIELDS)
					dialog.setMessage(getString(R.string.dialog_city_selection_incomplete_error));
				else if (id == DIALOG_ERROR_CITY_ALREADY_EXISTS)
					dialog.setMessage(getString(R.string.dialog_city_selection_city_already_exists_error));

				result = dialog;
		}
		return result;
	}

	private void initCountryList() throws IOException {
		countryNames = new ArrayList<String>();		
		String[] files = getAssets().list("countries");
		for (String fileName : files) {
			int pos = fileName.indexOf('.');	// each filename ends with '.txt' extension
			countryNames.add(fileName.substring(0, pos));	// we cut the extension
		}
	}
	
	private void initCityList(String fileName) throws IOException {
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		cityNames = new ArrayList<String>();
		cityIds = new ArrayList<String>();
		try {
			is = getAssets().open("countries/" + fileName + ".txt");	// may throw IOException
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			
			String city = null;
			while ((city = br.readLine()) != null) {
				int pos = city.indexOf('|');
				cityIds.add(city.substring(0, pos));
				cityNames.add(city.substring(pos + 1));
			}
		}
		finally {
			br.close();	// may throw IOException
		}
	}

}
